"""doc"""
from django.http import HttpRequest, JsonResponse
from django.utils import timezone


from app_common import (
    app_try,
    app_page,
    app_except,
    app_str_check,
    app_uuid,
    app_sms,
    json_response_utf8_ok,
)


from . import models, ser, wx_api, wx_pay, access_auth, user_car


def promotion_callback(upr: models.WxUserPaymentRecord) -> JsonResponse:
    upr.state = models.WxUserPaymentRecord.PaymentState.SUCCESS.value
    upr.pay_at = timezone.now()
    upr.save()

    # 为用户余额充值
    _user = (
        models.WxUser.objects.filter(deleted=False)
        .filter(openid=upr.openid)
        .select_for_update()
        .first()
    )
    if not _user:
        raise app_except.ObjNotExist(msg=f"openid: {upr.openid}")

    total_recharge = upr.total_fee + upr.score
    _user.remain_money += total_recharge
    _user.total_recharge += upr.total_fee
    _user.save()

    # 添加充值记录
    models.WxUserRemainMoneyRecord(
        user_uuid=_user.uuid,
        remain_money=_user.remain_money,
        actual_payment=upr.total_fee,
        score=upr.score,
    ).save()

    # 发送余额变更短信
    app_sms.send_sms_remain_money_change(
        receiver=_user.telephone,
        change_type=app_sms.SMS_TYPE.RECHARGE.value,
        change_money=total_recharge,
        remain_money=_user.remain_money,
    )

    data = {"errcode": 0, "errmsg": ""}
    return json_response_utf8_ok(
        data,
    )


def shopping_callback(upr: models.WxUserPaymentRecord) -> JsonResponse:
    upr.state = models.WxUserPaymentRecord.PaymentState.SUCCESS.value
    upr.pay_at = timezone.now()
    upr.save()

    # 清空购物车
    shopping = (
        models.StoreShopping.objects.filter(payment_record_uuid=upr.uuid)
        .select_for_update()
        .first()
    )
    shopping.state = models.StoreShopping.ShoppingState.PAID.value
    shopping.save()

    objs = (
        models.StoreGoodCarContent.objects.filter(deleted=False)
        .filter(user_uuid=shopping.user_uuid)
        .filter(created_at__lt=shopping.created_at)
        .select_for_update()
    )
    clear_count = user_car.clear_user_car(objs)
    if clear_count == 0:
        raise app_except.ValueErr(f"购物车清空失败, 数量为 0, 用户id: {shopping.user_uuid}")

    # 为用户余额充值
    _user = (
        models.WxUser.objects.filter(deleted=False)
        .filter(openid=upr.openid)
        .select_for_update()
        .first()
    )
    if not _user:
        raise app_except.ObjNotExist(msg=f"openid: {upr.openid}")

    total_recharge = upr.total_fee + upr.score
    _user.remain_money += total_recharge
    _user.total_recharge += upr.total_fee
    _user.save()

    # 添加充值记录
    models.WxUserRemainMoneyRecord(
        user_uuid=_user.uuid,
        remain_money=_user.remain_money,
        actual_payment=upr.total_fee,
        score=upr.score,
    ).save()

    data = {"errcode": 0, "errmsg": ""}
    return json_response_utf8_ok(
        data,
    )
